//
//  HJDataPikerView.m
//  project
//
//  Created by jc on 2019/5/11.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJDataPikerView.h"
#import "NSDate+YFExtension.h"

@interface HJDataPikerView ()<UIPickerViewDelegate,UIPickerViewDataSource>

/**
 背景
 */
@property (weak, nonatomic) IBOutlet UIView *bgView;

/**
 中间视图
 */
@property (weak, nonatomic) IBOutlet UIView *contentView;

/**
 title
 */
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

/**
 取消按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *cancleBtn;

/**
 完成按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *successBtn;

/**
 时间选择器
 */
@property (weak, nonatomic) IBOutlet UIPickerView *picker;

/**
 年
 */
@property (nonatomic, strong) NSMutableArray <NSString *> *yearArray;

/**
 月
 */
@property (nonatomic, strong) NSMutableArray <NSString *> *monthArray;

/**
 日
 */
@property (nonatomic, strong) NSMutableArray <NSString *> *dayArray;
/**
 选中的年份 默认当前时间的年份
 */
@property (nonatomic,assign) NSInteger selectedYear;

/**
 选中的月份 默认当前时间的月份
 */
@property (nonatomic, assign) NSInteger selectedMonth;

/**
 选中的日 默认当前时间的日
 */
@property (nonatomic, assign) NSInteger selectedDay;
/**
 选中的年月日 默认当前时间的年月日
 */
@property (nonatomic, strong) NSString * selectedDate;

@end

@implementation HJDataPikerView

+(instancetype)initDatePicker {
    HJDataPikerView * datePicker = [[HJDataPikerView alloc]init];
    datePicker.frame = [UIScreen mainScreen].bounds;
    return datePicker;
}

-(void)show {
    self.alpha = 0;
    self.contentView.transform = CGAffineTransformMakeScale(0, 0);
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.alpha = 1;
        self.contentView.transform = CGAffineTransformMakeScale(2.0,2.0);
        self.contentView.transform = CGAffineTransformMakeScale(1, 1);
    } completion:^(BOOL finished) {
        self.contentView.transform = CGAffineTransformIdentity;
    }];
}
-(void)dismiss {
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.alpha = 0;
        self.contentView.transform = CGAffineTransformMakeScale(0, 0);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        self.alpha = 1;
        self.contentView.transform = CGAffineTransformIdentity;
    }];
}

-(instancetype)init {
    if (self == [super init]) {
        self = [[NSBundle mainBundle]loadNibNamed:@"HJDataPikerView" owner:nil options:nil].firstObject;
        self.picker.delegate = self;
        self.picker.dataSource = self;
        [self.contentView rounded:UIRectCornerAllCorners radius:6];
//        [self setupShadowWithView:self.cancleBtn];
//        [self setupShadowWithView:self.successBtn];
        self.selectedYear = [NSDate date].currentYear;
        self.selectedMonth = [NSDate date].currentMonth;
        self.selectedDay = [NSDate date].currentDay;
        self.selectedDate = [NSString stringWithFormat:@"%zd年%zd月%zd日",self.selectedYear,self.selectedMonth,self.selectedDay];
        // 刷新UI
        [self.picker reloadAllComponents];
        NSString *selectyearString = [NSString stringWithFormat:@"%zd", self.selectedYear];
        [self.picker selectRow:[self indexInArray:self.yearArray value:selectyearString] inComponent:0 animated:YES];
        
        NSString *selectedMonthString = [NSString stringWithFormat:@"%zd", self.selectedMonth];
        [self.picker selectRow:[self indexInArray:self.monthArray value:selectedMonthString] inComponent:1 animated:YES];
        
        NSString *selectedDayString = [NSString stringWithFormat:@"%zd", self.selectedDay];
        [self.picker selectRow:[self indexInArray:self.dayArray value:selectedDayString] inComponent:2 animated:YES];
        
        @weakify(self)
        // 取消按钮
        [[self.cancleBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self dismiss];
        }];
        // 完成
        [[self.successBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self dismiss];
            NSString * year = [NSString stringWithFormat:@"%zd",self.selectedYear];
            NSString * month = [NSString stringWithFormat:@"%zd",self.selectedMonth];
            NSString * day = [NSString stringWithFormat:@"%zd",self.selectedDay];
            LKLog(@"%@,%@,%@   %@",year,month,day,self.selectedDate);
            if (self.completeDatePickerBlock) {
                self.completeDatePickerBlock(year, month, day, self.selectedDate);
            }
        }];
    }
    return self;
}
// 年
-(NSMutableArray <NSString *>*)yearArray {
    if (!_yearArray) {
        _yearArray = [NSMutableArray array];
        for (int year = 1970; year <= [NSDate date].currentYear; year++) {
            NSString *str = [NSString stringWithFormat:@"%d", year];
            [_yearArray addObject:str];
        }
    }
    return _yearArray;
}
// 月
-(NSMutableArray<NSString *> *)monthArray {
    if (!_monthArray) {
        _monthArray = [NSMutableArray array];
        for (int month = 1; month <= 12; month++) {
            NSString *str = [NSString stringWithFormat:@"%2d", month];
            [_monthArray addObject:str];
        }
    }
    return _monthArray;
}
// 日
-(NSMutableArray<NSString *> *)dayArray {
    if (!_dayArray) {
        NSInteger length = [NSDate daysWithYear:self.selectedYear month:self.selectedMonth];
        _dayArray= [NSMutableArray arrayWithCapacity:length];
        NSInteger day = 1;
        for (int i = 0; i < length; i++) {
            [_dayArray addObject:[NSString stringWithFormat:@"%zd", day]];
            day += 1;
        }
    }
    return _dayArray;
}


#pragma mark --UIPickerViewDelegate,UIPickerViewDataSource
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (component) {
        case 0:
            return self.yearArray.count;
            break;
        case 1:
            return self.monthArray.count;
            break;
        default:
            return self.dayArray.count;
            break;
    }
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UIColor *lineColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1];
    ((UIView *)[pickerView.subviews objectAtIndex:1]).backgroundColor = lineColor;
    ((UIView *)[pickerView.subviews objectAtIndex:2]).backgroundColor = lineColor;
    
    UILabel * label = [UILabel new];
    label.textColor = [UIColor blackColor];
    label.font = [UIFont fontWithName:@"PingFangSC-Medium" size:13];
    label.textAlignment = NSTextAlignmentCenter;

    switch (component) {
        case 0:
            label.text = self.yearArray[row];
            break;
        case 1:
            label.text = self.monthArray[row];
            break;
        default:
            label.text = self.dayArray[row];
            break;
    }
    return label;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    switch (component) {
        case 0:
            LKLog(@"%@年",self.yearArray[row]);
            [pickerView reloadComponent:1];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
            self.selectedYear = self.yearArray[row].integerValue;
            self.selectedMonth = self.monthArray[0].integerValue;
            self.selectedDay = self.dayArray[0].integerValue;
            break;
        case 1:
            LKLog(@"%@月",self.monthArray[row]);
            if (self.monthArray[row].integerValue >=[NSDate date].currentMonth && self.selectedYear == [NSDate date].currentYear) {
                [pickerView reloadComponent:1];
                [pickerView selectRow:[NSDate date].currentMonth-1 inComponent:1 animated:NO];
                self.selectedMonth = [NSDate date].currentMonth;
            }else {
                self.selectedMonth = self.monthArray[row].integerValue;
            }
            self.selectedDay = self.dayArray[0].integerValue;
            [pickerView reloadComponent:2];
            [pickerView selectRow:0 inComponent:2 animated:NO];
            break;
        default:
            LKLog(@"%@日",self.dayArray[row]);
            if (self.dayArray[row].integerValue >= [NSDate date].currentDay && self.selectedMonth == [NSDate date].currentMonth && self.selectedYear == [NSDate date].currentYear) {
                [pickerView reloadComponent:2];
                [pickerView selectRow:[NSDate date].currentDay-1 inComponent:2 animated:NO];
                self.selectedDay = [NSDate date].currentDay;
            }else {
                self.selectedDay = self.dayArray[row].integerValue;
            }
            
            break;
    }
    self.selectedDate = [NSString stringWithFormat:@"%zd年%zd月%zd日",self.selectedYear,self.selectedMonth,self.selectedDay];
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 38;
}
#pragma mark - 获取元素在数组中的位置
- (NSInteger)indexInArray:(NSArray <NSString *> *)array value:(NSString *)value {
    __block NSInteger index = 0;
    [array enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (value.integerValue == obj.integerValue) {
            index = idx;
        }
    }];
    return index;
}

#pragma nark --修改UI文字
-(void)setTitle:(NSString *)title {
    self.titleLabel.text = title;
}
-(void)setCancleTitle:(NSString *)cancleTitle {
    [self.cancleBtn setTitle:cancleTitle forState:0];
}
-(void)setSucessTitle:(NSString *)sucessTitle {
    [self.successBtn setTitle:sucessTitle forState:0];
}

@end
